from fastapi.routing import APIRoute

from fastapiApp.models.admin import Api_Mo
from fastapiApp.schemas.api_scheams import ApiCreate, ApiUpdate
from fastapi.exceptions import HTTPException

class ApiController(Api_Mo):
    def __init__(self):
        self.model = Api_Mo

    # 判断name是否已经存在
    async def is_exist(self,obj_in : ApiCreate) -> int:
        if await self.model.filter(path=obj_in.path).exists():
            raise HTTPException(status_code=400, detail="API地址已存在")
        return 0

    # 查看API list
    async def list(self, page: int, page_size: int, path: str, summary: str, tags: str):
        query = await self.model.filter(path__icontains = path,summary__icontains = summary,tags__icontains = tags).offset((page - 1) * page_size).limit(page_size)
        count = await self.model.filter(path__icontains = path,summary__icontains = summary,tags__icontains = tags).count()
        data_list = [
            await role.to_dict()
            for role in query
        ]
        return count,data_list

    # 修改API
    async def update_api(self, obj_in:ApiUpdate) -> None:
        api = await self.model.get(id=obj_in.id)
        api.path = obj_in.path
        api.summary = obj_in.summary
        api.tags = obj_in.tags
        api.method = obj_in.method
        await api.save()

    # 刷新全部API 数据
    async def refresh_api(self):
        from fastapiApp import app

        # 删除废弃API数据
        all_api_list = []
        for route in app.routes:
            # 只更新有鉴权的API
            # if isinstance(route, APIRoute) and len(route.dependencies) > 0:
            if isinstance(route, APIRoute):
                all_api_list.append((list(route.methods)[0], route.path_format))
        delete_api = []
        for api in await Api_Mo.all():
            if (api.method, api.path) not in all_api_list:
                delete_api.append((api.method, api.path))
        for item in delete_api:
            method, path = item
            print(f"API Deleted {method} {path}")
            # logger.debug(f"API Deleted {method} {path}")
            await Api_Mo.filter(method=method, path=path).delete()

        # 更新API 数据
        for route in app.routes:
            if isinstance(route, APIRoute):
            # if isinstance(route, APIRoute) and len(route.dependencies) > 0:
                method = list(route.methods)[0]
                path = route.path_format
                summary = route.summary
                tags = list(route.tags)[0]
                api_obj = await Api_Mo.filter(method=method, path=path).first()
                # 存在 update 否则 creat
                if api_obj:
                    await api_obj.update_from_dict(dict(method=method, path=path, summary=summary, tags=tags)).save()
                else:
                    print(f"API Created {method} {path}")
                    # logger.debug(f"API Created {method} {path}")
                    await Api_Mo.create(**dict(method=method, path=path, summary=summary, tags=tags))
        print("finsh")

api_controller = ApiController()
